Fortran For Fun 并行之mpi

MPI是常用的并行编程库,可以安装openmpi或mpich来获得mpi的API。

learn_mpi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
program learn_mpi
use mpi
implicit none
integer :: ip, np, ctx, info
real :: wtime
call mpi_init(info)
call mpi_comm_size(MPI_COMM_WORLD, np, info)
call mpi_comm_rank(MPI_COMM_WORLD, ip, info)
if(ip == 0) then
print*, 'number of process = ',np
wtime = mpi_wtime()
endif
print*, 'hello mpi from process ',ip
if(ip==0) then
wtime = mpi_wtime() - wtime
print*, 'Time elapsed = ',wtime,' seconds.'
endif
call mpi_finalize(info)
end program learn_mpi

结果

执行mpirun -n 4 learn_mpi得到

1
2
3
4
5
6
number of process = 4
hello mpi from process 0
hello mpi from process 1
hello mpi from process 2
hello mpi from process 3
Time elapsed = 4.0020095184445381E-006 seconds.

open-mpi